import msg from '@/components/msg/msg'
import md5encryption from 'js-md5'
const jieliu = () => {
  let timer: number | null = null
  return (cb: Function, time: number = 300) => {
    if (timer) {
      clearTimeout(timer)
    }
    timer = setTimeout(() => {
      cb()
    }, time)
  }
}
const jieliuUtil = jieliu()
const fangdou = () => {
  let ifNext = true
  return (cb: Function, time: number, callBack?: Function) => {
    if (ifNext) {
      ifNext = false
      cb()
      setTimeout(() => {
        callBack && callBack()
        ifNext = true
      }, time)
    }
  }
}
const fangdouUtil = fangdou()

const limitRequest = (arr: (() => Promise<unknown>)[] = [], max = 3, cb?: Function, finishCb?: Function) => {
  let index: number | null = 0
  let reqArr = new Array(max).fill(null)
  const res: unknown[] = []
  reqArr = reqArr.map(() => {
    return new Promise((resolve) => {
      const run = () => {
        if (index === null || index >= arr.length) {
          resolve(res)
          return
        }
        const cur = index
        index++
        arr[cur]()
          .then((result) => {
            res[cur] = result
            cb && cb(result, cur)
          })
          .catch((e) => {
            res[cur] = e
          })
          .finally(() => {
            run()
          })
      }
      run()
    })
  })
  Promise.all(reqArr).then((res) => {
    finishCb && finishCb(res, index)
  })
  return () => {
    index = null
  }
}
const md5 = (originTarget: string) => {
  return md5encryption(originTarget + 'ttzxhEncryption')
}

// 安全json解析
export const safeJsonParse = (json: string) => {
  try {
    const result = JSON.parse(json)
    return { success: true, result }
  } catch (e) {
    return { success: false, result: json }
  }
}

// json美化
export const jsonBeautiful = (json: string) => {
  const { success, result } = safeJsonParse(json)
  if (success) {
    return JSON.stringify(result, null, 2)
  } else {
    return result
  }
}

// 复制
export const copy = async (text: string) => {
  await navigator.clipboard.writeText(text)
  msg.success('复制成功')
}

export type ItemTypeFromArray<T> = T extends Array<infer R> ? R : never

export { limitRequest }
export { jieliuUtil }
export { fangdouUtil }
export { md5 }
